package cn.wowjoy.office.applystock;

import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.ApplyItemAdapter;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.ResultException;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.ApplyFormQueryConditions;
import cn.wowjoy.office.data.response.ApplyHeadInfoResponse;
import cn.wowjoy.office.data.response.ApplyHeadListResponse;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class ApplyStockViewModel extends NewBaseViewModel {

    @Inject
    ApiService apiService;
    private  int type;
    private int startIndex = 0;
    private int pageSize = 10;
    private boolean isCanCreate;

    private String stroageCode;
    private String status;

    private String isEnd;

    ApplyItemAdapter adapter = new ApplyItemAdapter();
    LRecyclerViewAdapter lAdapter = new LRecyclerViewAdapter(adapter);

    MediatorLiveData<LiveDataWrapper<List<PopuModel>>> permisson = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<ApplyHeadListResponse>> reponses = new MediatorLiveData<>();
    MediatorLiveData<ApplyHeadInfoResponse> jump = new MediatorLiveData<>();

    public void setStroageCode(String stroageCode) {
        this.stroageCode = stroageCode;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getStatus() {
        return status;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setIsEnd(String isEnd) {
        this.isEnd = isEnd;
    }

    public void setCanCreate(boolean canCreate) {
        isCanCreate = canCreate;
    }

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        getList(ref);
    }

    @Inject
    public ApplyStockViewModel(@NonNull NewMainApplication application) {
        super(application);
        adapter.setHandler(this);
    }

    @Override
    public void onCreateViewModel() {

    }

    public void jump(ApplyHeadInfoResponse response){
        ARouter.getInstance().build("/applystock/detail/applyheaddetail")
                .withString("headCode",response.getHeadCode())
                .withInt("type",type)
                .withBoolean("isCanCreate",isCanCreate)
                .navigation();
    }

    public void getStorageUserId() {
        permisson.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getStock()
                .flatMap(new ResultDataParse<List<PopuModel>>())
                .compose(new RxSchedulerTransformer<List<PopuModel>>())
                .subscribe(new Consumer<List<PopuModel>>() {
                    @Override
                    public void accept(List<PopuModel> taskListResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        if (null != taskListResponse){
                            stroageCode = taskListResponse.get(0).getStorageCode();
                            permisson.setValue(LiveDataWrapper.success(taskListResponse));
                        } else {
                            permisson.setValue(LiveDataWrapper.error(new ResultException("没有权限",1),null));
                        }


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        permisson.setValue(LiveDataWrapper.error(throwable,null));


                    }
                });
        addDisposable(disposable);
    }

    public void setData(boolean isRefresh, List<ApplyHeadInfoResponse> data) {

        if (isRefresh) {
            adapter.refresh(data);
        } else {
            if (data != null)
                adapter.loadMore(data);
        }
        lAdapter.removeFooterView();
        if (!isRefresh && (null == data || data.isEmpty() )){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
            lAdapter.addFooterView(view);

        }
        lAdapter.notifyDataSetChanged();
        refreshComplete();
    }


    public void getList(boolean isRefresh){
        switch (type){
            case Constants.RECEIPTS_CODE_APPLY:
                getApplyHeadList(isRefresh);
                break;
            case Constants.RECEIPTS_CODE_APPLY_FOR:
                break;
            case Constants.RECEIPTS_CODE_ALLOT:

                getApplyForList(isRefresh);
                break;
        }
    }

    /**
     * status 待出库 8-3 完成8-5
     */

    public void getApplyHeadList(boolean isRefresh){
        ApplyFormQueryConditions applyFormQueryConditions;
        if (isRefresh){
            startIndex = 0;
        } else {
            ++startIndex;
        }
        reponses.setValue(LiveDataWrapper.loading(null));
        if("8-5".equalsIgnoreCase(status)){
            applyFormQueryConditions = new ApplyFormQueryConditions(stroageCode, startIndex, pageSize,"666");
        }else {
            applyFormQueryConditions = new ApplyFormQueryConditions(stroageCode, status,startIndex, pageSize);
        }
        Disposable disposable = apiService.getApplyHeadList(applyFormQueryConditions)
                .flatMap(new ResultDataParse<ApplyHeadListResponse>())
                .compose(new RxSchedulerTransformer<ApplyHeadListResponse>())
                .subscribe(new Consumer<ApplyHeadListResponse>() {
                    @Override
                    public void accept(ApplyHeadListResponse taskListResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        reponses.setValue(LiveDataWrapper.success(taskListResponse));
                        if (taskListResponse == null){
                            setData(isRefresh,null);
                        } else {
                            setData(isRefresh,taskListResponse.getList());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        reponses.setValue(LiveDataWrapper.error(throwable,null));

                    }
                });
        addDisposable(disposable);
    }

    /**
     * status 待出库 38-8
     * isEnd 完成 y
     */
    public void getApplyForList(boolean isRefresh){
        if (isRefresh){
            startIndex = 0;
        } else {
            ++startIndex;
        }
        reponses.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getAllotList(status,null,stroageCode,null,isEnd,startIndex,pageSize)
                .flatMap(new ResultDataParse<ApplyHeadListResponse>())
                .compose(new RxSchedulerTransformer<ApplyHeadListResponse>())
                .subscribe(new Consumer<ApplyHeadListResponse>() {
                    @Override
                    public void accept(ApplyHeadListResponse taskListResponse) throws Exception {
                        //获取的数据发送给Activity来使用
                        reponses.setValue(LiveDataWrapper.success(taskListResponse));
                        if (taskListResponse == null){
                            setData(isRefresh,null);
                        } else {
                            setData(isRefresh,taskListResponse.getList());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //异常处理
                        reponses.setValue(LiveDataWrapper.error(throwable,null));

                    }
                });
        addDisposable(disposable);
    }
}
